<?php

/**
 * LoginForm class.
 * LoginForm is the data structure for keeping
 * user login form data. It is used by the 'login' action of 'SiteController'.
 */
class AdminhtmlLoginForm extends CFormModel
{
	public $username;
	public $password;
	public $rememberMe;
	public $verifyCode;
	
	private $_identity;

	/**
	 * Declares the validation rules.
	 * The rules state that username and password are required,
	 * and password needs to be authenticated.
	 */
	public function rules()
	{
		return array(
			array('username, password', 'required'),
			array('rememberMe', 'boolean'),
			array('password', 'authenticate'),
			array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			'rememberMe'=>'记住帐号',
			'username'=>'管理员帐号',
			'password'=>'管理员密码',
			'verifyCode'=>'验证码',
		);
	}

	/**
	 * Authenticates the password.
	 * This is the 'authenticate' validator as declared in rules().
	 */
	public function authenticate($attribute,$params)
	{
		if(!$this->hasErrors())
		{
			$this->_identity=new AdminIdentity($this->username,$this->password);
			if(!$this->_identity->authenticate()) {
				switch ($this->_identity->errorCode ) {
					case AdminIdentity::ERROR_STATE_INVALID:
					    $this->addError('username','该账户处于非激活状态.');
					    break;
					default:
						$this->addError('password','无效的帐号或者密码.');
					    break;
				}
			}
		}
	}

	/**
	 * Logs in the user using the given username and password in the model.
	 * @return boolean whether login is successful
	 */
	public function login()
	{
		if($this->_identity===null)
		{
			$this->_identity=new AdminIdentity($this->username,$this->password);
			$this->_identity->authenticate();
		}
		
		if($this->_identity->errorCode===AdminIdentity::ERROR_NONE)
		{
			$duration=$this->rememberMe ? 3600* 24* AdminhtmlSession::REMEMBER_DAYS : 0; // 30 days
			Yii::app()->admin->login($this->_identity, $duration);
			
			$model= AdminhtmlAdmin::model()->loadByAccount($this->username);
			
			$roleId= $model->getAttribute('role_id');
			$roleAcl= AdminhtmlRole::model()->getOneAclArray($roleId);
			Yii::app()->admin->setState('admin_id', $model->getAttribute('admin_id') );
			Yii::app()->admin->setState('area', Yii::app()->params['area']['adminhtml'] );
			Yii::app()->admin->setState('allowActions', $roleAcl );
			Yii::app()->admin->setState('menuArray', AdminhtmlHelper::getMenuArray() );
			//TODO set other variables.
			
			$model->setAttribute('update_time', date('Y-m-d H:i:s'));
			$model->save();
			
			return true;
			
		} else {
			return false;
		}
	}
	
	
	
}
